<template>
  <div class="location-detector" @click="handleLocationClick">
    <i class="fas fa-map-marker-alt"></i>
    <div class="location-text">
      <span class="text-xs text-white">{{ $t('所在地区') }}</span>
      <span class="text-sm text-white font-bold">{{ displayLocation }}</span>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import { getIpLocation } from '@/utils/ipLocation'
import i18n from "@/locale";
const { t } = i18n.global

export default defineComponent({
  name: 'LocationDetector',
  props: {
    defaultLocation: {
      type: String,
      default: t('正在获取...')
    }
  },
  setup(props) {
    const location = ref<{ city: string; region: string; country: string } | null>(null)
    const isLoading = ref(true)
    const error = ref<string | null>(null)

    const displayLocation = computed(() => {
      if (isLoading.value) return props.defaultLocation
      if (error.value) return props.defaultLocation
      if (location.value) {
        return location.value.city || location.value.region || location.value.country
      }
      return props.defaultLocation
    })

    const fetchLocation = async () => {
      try {
        isLoading.value = true
        error.value = null
        const ipInfo = await getIpLocation()
        if (ipInfo) {
          location.value = ipInfo
        } else {
          throw new Error('获取位置失败')
        }
      } catch (err) {
        console.error('获取位置信息失败:', err)
        error.value = err instanceof Error ? err.message : t('未知错误')
      } finally {
        isLoading.value = false
      }
    }

    const handleLocationClick = () => {
      console.log('Current location:', location.value || '使用默认位置')
    }

    onMounted(() => {
      fetchLocation()
    })

    return {
      displayLocation,
      handleLocationClick
    }
  }
})
</script>

<style lang="scss" scoped>
.location-detector {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  padding: 2px 8px;
  border: 1px solid transparent;
  border-radius: $border-radius-sm;

  &:hover {
    border-color: $text-white;
  }

  .fa-map-marker-alt {
    font-size: $font-size-lg;
    color: $text-white;
  }

  .location-text {
    display: flex;
    flex-direction: column;
    line-height: 1.2;

    .text-xs {
      font-size: 11px;
      opacity: 0.9;
    }

    .text-sm {
      font-size: 13px;
    }
  }
}
</style>
